package com.fengmi.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fengmi.vo.ResultVO;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>title: com.fengmi.controller</p>
 * <p>Company: wendao</p>
 * author zhuximing
 * date 2021/7/7
 * description:
 */
@RestController
@CrossOrigin
public class UpLoadController {

    @Autowired
    private ObjectMapper objectMapper;


    @Value("${qiniu.accessKey}")
    String accessKey ;
    @Value("${qiniu.secretKey}")
    String secretKey ;
    @Value("${qiniu.bucket}")
    String bucket ;


    @PostMapping("upload")
    //参数名称必须和input的name保持一致
    public ResultVO upload (MultipartFile headImg) throws Exception{



        //获取文件名
//        System.out.println(headImg.getOriginalFilename());


        //文件内容
        byte[] bytes = headImg.getBytes();


        //落地？
        //方案一：使用第三方的文件存储系统  比如七牛云 、阿里云【OSS 对象存储】、腾讯云【对象存储】
        //方案二：自己搭建文件服务器【fastdfs】【支持分布式存储】



        //上传到七牛云
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = headImg.getOriginalFilename();  //文件名
        String url = "";
        try {
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(bytes, key, upToken);//上传
                //解析上传成功的结果
                DefaultPutRet putRet = objectMapper.readValue(response.bodyString(), DefaultPutRet.class);


                System.out.println(putRet.key);
                System.out.println(putRet.hash);

                //图片的访问地址
                url= "http://qufdpcyan.hn-bkt.clouddn.com/"+putRet.key;
                System.out.println(url);



            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
            ex.printStackTrace();
        }





        return new ResultVO(true, "success", url);
    }

}